//
//  MKMusicViewController.m
//  singForYou
//
//  Created by nicolas on 2017/3/7.
//  Copyright © 2017年 nicolas. All rights reserved.
//

/**
 遇到问题：1、把锁屏代码放在定时器方法后，锁屏时间会出错，如果点击返回按钮在点击另一首歌进入，此时进入锁屏，发现锁屏界面出现两首歌切换的情况，同时远程控制实效
 */

#import "MKMusicViewController.h"

#import <Masonry.h>
#import <MJExtension/MJExtension.h>

#import "MKMusciModel.h"
#import "MKMusicManager.h"
#import "MKMusicTool.h"
#import "MKLyricsTool.h"
#import "MKLyricsModel.h"
#import "MKLyricLabel.h"
//锁屏界面更新需要用到MPNowPlayingInfoCenter
#import <MediaPlayer/MediaPlayer.h>

#import "UIImage+Lyrics.h"

#import <AVFoundation/AVFoundation.h>

@interface MKMusicViewController ()
//背景图片
@property (strong, nonatomic) UIImageView *bgImageView;
//歌名
@property (strong, nonatomic) UILabel *songNameLbl;
//歌手
@property (strong, nonatomic) UILabel *singerLbl;
//歌手图片
@property (strong, nonatomic) UIImageView *singerInfosImageView;
//歌词
@property (strong, nonatomic) MKLyricLabel *lyricsLbl;
//歌词信息
@property (strong, nonatomic) UILabel *infoLbl;
//左侧时间
@property (strong, nonatomic) UILabel *leftTimeLbl;
//右侧时间
@property (strong, nonatomic) UILabel *rightTimeLbl;
//进度条
@property (strong, nonatomic) UISlider *progressSlider;
//上一首歌
@property (strong, nonatomic) UIButton *previousBtn;
//播放
@property (strong, nonatomic) UIButton *playBtn;
//下一首歌
@property (strong, nonatomic) UIButton *nextBtn;

//歌曲列表
@property (strong, nonatomic) NSArray *musicList;
//歌词列表
@property (strong, nonatomic) NSArray *lyricsList;
//播放工具
@property (strong, nonatomic) MKMusicManager *musicManager;
@property (strong, nonatomic) MKMusicTool *musicTool;
@property (strong, nonatomic) MKLyricsTool *lyricsTool;
//当前的歌词搜索索引
@property (assign, nonatomic) NSUInteger lyricsIndex;
//定时器
@property (strong, nonatomic) NSTimer *progressTimer;
@end

@implementation MKMusicViewController

//单独定制白色电池条
- (UIStatusBarStyle)preferredStatusBarStyle {
    return UIStatusBarStyleLightContent;
}

#pragma mark - 发生远程控制事件时执行
- (void)remoteControlReceivedWithEvent:(UIEvent *)event {
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:{
            [self didClickPlayBtn:self.playBtn];
            break;
        }
        case UIEventSubtypeRemoteControlPause:{
            [self didClickPlayBtn:self.playBtn];
            break;
        }
        case UIEventSubtypeRemoteControlNextTrack:{
            [self didClickNextBtn:self.nextBtn];
            break;
        }
        case UIEventSubtypeRemoteControlPreviousTrack:{
            [self didClickPreviousBtn:self.previousBtn];
            break;
        }
        default:
            break;
    }
}
#pragma mark - Life circle
- (void)viewDidLoad {
    [super viewDidLoad];
    //实例化
    self.musicManager = [MKMusicManager shareInstance];
    self.musicTool = [[MKMusicTool alloc] init];
    self.lyricsTool = [[MKLyricsTool alloc] init];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self prepareUI];
    [self primaryMusicPlay];
    self.playBtn.selected = YES;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    self.singerInfosImageView.layer.cornerRadius = self.singerInfosImageView.bounds.size.width * 0.5;
//    self.singerInfosImageView.layer.masksToBounds = YES;
    self.singerInfosImageView.clipsToBounds = YES;
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];
    [self.progressTimer invalidate];
    //置空下一次懒加载才会生效
    self.progressTimer = nil;
}
- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark - Private methods
//制作模糊背景
- (void)makeBlurEffect {
    // UIBlurEffect表示模糊效果
    UIBlurEffect *effect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleDark];
    //  效果视图, 得到效果对应的View
    UIVisualEffectView *effectView = [[UIVisualEffectView alloc] initWithEffect:effect];
    [self.bgImageView addSubview:effectView];
    
    // 添加约束
    [effectView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(UIEdgeInsetsMake(0, 0, 0, 0));
    }];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(interruptionAction:) name:AVAudioSessionInterruptionNotification object:nil];
    
}
//初始化控件
- (void)prepareUI {
    //背景图片
    UIImageView *bgImageView = [[UIImageView alloc] init];
    [self.view addSubview:bgImageView];
    [bgImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view);
        make.top.equalTo(self.view).offset(64);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
    }];
    self.bgImageView = bgImageView;
    [self makeBlurEffect];
    //歌名
    UILabel *songNameLbl = [[UILabel alloc] init];
    songNameLbl.textAlignment = NSTextAlignmentCenter;
    songNameLbl.font = [UIFont systemFontOfSize:20];
    songNameLbl.textColor = [UIColor whiteColor];
    [self.view addSubview:songNameLbl];
    [songNameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.top.equalTo(self.view).offset(84);
        make.height.mas_equalTo(40);
    }];
    self.songNameLbl = songNameLbl;
    //歌手
    UILabel *singerLbl = [[UILabel alloc] init];
    singerLbl.textColor = [UIColor whiteColor];
    singerLbl.textAlignment = NSTextAlignmentCenter;
    singerLbl.font = [UIFont systemFontOfSize:20];
    [self.view addSubview:singerLbl];
    [singerLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view.mas_left).offset(20);
        make.right.equalTo(self.view.mas_right).offset(-20);
        make.top.equalTo(songNameLbl.mas_bottom).offset(30);
        make.height.mas_equalTo(40);
    }];
    self.singerLbl = singerLbl;
    //图片
    UIImageView *singerInfosImageView = [[UIImageView alloc] init];
    singerInfosImageView.image = [UIImage imageNamed:@"blue"];
    [self.view addSubview:singerInfosImageView];
    [singerInfosImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(singerLbl.mas_bottom).offset(30);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(160);
    }];
    self.singerInfosImageView = singerInfosImageView;
    //歌词
    MKLyricLabel *lyricsLbl = [[MKLyricLabel alloc] init];
    lyricsLbl.numberOfLines= 0;
    lyricsLbl.textColor= [UIColor whiteColor];
    lyricsLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:lyricsLbl];
    [lyricsLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
        make.top.equalTo(singerInfosImageView.mas_bottom).offset(10);
        make.height.mas_equalTo(50);
    }];
    self.lyricsLbl = lyricsLbl;
    //信息
    UILabel *infoLbl = [[UILabel alloc] init];
    infoLbl.textColor = [UIColor whiteColor];
    infoLbl.textAlignment = NSTextAlignmentCenter;
    [self.view addSubview:infoLbl];
    [infoLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(lyricsLbl.mas_bottom).offset(15);
        make.height.mas_equalTo(20);
    }];
    self.infoLbl = infoLbl;
    //左侧歌曲时间
    UILabel *leftTimeLbl = [[UILabel alloc] init];
    leftTimeLbl.text = @"00:00";
    leftTimeLbl.textColor = [UIColor whiteColor];
    leftTimeLbl.textAlignment = NSTextAlignmentLeft;
    [self.view addSubview:leftTimeLbl];
    [leftTimeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(15);
        make.top.equalTo(infoLbl.mas_bottom);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    self.leftTimeLbl = leftTimeLbl;
    //歌曲时长
    UILabel *rightTimeLbl = [[UILabel alloc] init];
    rightTimeLbl.text = @"03:00";
    rightTimeLbl.textColor = [UIColor whiteColor];
    rightTimeLbl.textAlignment = NSTextAlignmentRight;
    [self.view addSubview:rightTimeLbl];
    [rightTimeLbl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-15);
        make.top.equalTo(infoLbl.mas_bottom);
        make.width.mas_equalTo(60);
        make.height.mas_equalTo(40);
    }];
    self.rightTimeLbl = rightTimeLbl;
    //进度条
    UISlider *progressSlider = [[UISlider alloc] init];
    progressSlider.thumbTintColor = [UIColor greenColor];
    progressSlider.minimumTrackTintColor = [UIColor greenColor];
    progressSlider.maximumTrackTintColor = [UIColor grayColor];
    [self.view addSubview:progressSlider];
    [progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftTimeLbl.mas_right).offset(2);
        make.top.equalTo(infoLbl.mas_bottom);
        make.right.equalTo(rightTimeLbl.mas_left).offset(-4);
        make.height.mas_equalTo(40);
    }];
    [progressSlider addTarget:self action:@selector(touchDownSliderAction:) forControlEvents:UIControlEventTouchDown];
    [progressSlider addTarget:self action:@selector(changedSliderAction:) forControlEvents:UIControlEventValueChanged];
    [progressSlider addTarget:self action:@selector(touchUpInsiderAction:) forControlEvents:UIControlEventTouchUpInside];
    self.progressSlider = progressSlider;
    //上一首歌
    UIButton *previousBtn = [[UIButton alloc] init];
    [previousBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_pre_normal"] forState:UIControlStateNormal];
    [previousBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_pre_highlight" ]forState:UIControlStateHighlighted];
    [self.view addSubview:previousBtn];
    [previousBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(75);
        make.bottom.equalTo(self.view).offset(-30);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];
    [previousBtn addTarget:self action:@selector(didClickPreviousBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.previousBtn = previousBtn;
    //播放
    UIButton *playBtn = [[UIButton alloc] init];
    [playBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_play_normal"] forState:UIControlStateNormal];
    [playBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_play_highlight"] forState:UIControlStateHighlighted];
    [playBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_pause_normal"] forState:UIControlStateSelected];
    [self.view addSubview:playBtn];
    [playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(previousBtn.mas_right).offset(20);
        make.bottom.equalTo(previousBtn).offset(-5);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];
    [playBtn addTarget:self action:@selector(didClickPlayBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.playBtn = playBtn;
    //下一首歌
    UIButton *nextBtn = [[UIButton alloc] init];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_next_normal"] forState:UIControlStateNormal];
    [nextBtn setBackgroundImage:[UIImage imageNamed:@"player_btn_next_highlight"] forState:UIControlStateHighlighted];
    [self.view addSubview:nextBtn];
    [nextBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(playBtn.mas_right).offset(20);
        make.bottom.equalTo(previousBtn);
        make.width.mas_equalTo(70);
        make.height.mas_equalTo(70);
    }];
    [nextBtn addTarget:self action:@selector(didClickNextBtn:) forControlEvents:UIControlEventTouchUpInside];
    self.nextBtn = nextBtn;
    
}

//上下震动换歌
- (void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event {
    
    if (motion == UIEventSubtypeMotionShake) {
        //下一首歌
    }
    
}

#pragma mark - Action
//点击上一首歌
- (void)didClickPreviousBtn:(UIButton *)sender {
    //改变歌曲的索引(顺序播放)
    if (self.musicIndex == 0) {
        self.musicIndex = self.musicList.count-1;
    }else {
        self.musicIndex--;
    }
    [self primaryMusicPlay];
}
//点击播放歌曲
- (void)didClickPlayBtn:(UIButton *)sender {
    //按钮状态改变
    sender.selected = !self.musicManager.isPlaying;
    //当前歌曲模型
    if (self.musicManager.isPlaying) {
        [self.musicManager pauseMusic];
        //暂停时，停止定时器
        [self.progressTimer invalidate];
        self.progressTimer = nil;
    }else {
        [self primaryMusicPlay];
    }
}
//点击下一首歌曲
- (void)didClickNextBtn:(UIButton *)sender {
    if (self.musicIndex == self.musicList.count-1) {
        self.musicIndex = 0;
    }else {
        self.musicIndex++;
    }
    [self primaryMusicPlay];
}

- (void)touchDownSliderAction:(UISlider *)sender {
    [self.progressTimer invalidate];
    self.progressTimer = nil;
}

- (void)changedSliderAction:(UISlider *)sender {
    
     self.leftTimeLbl.text = [self.musicTool formatterTimeWithTimeInterval:sender.value]         ;
}

- (void)touchUpInsiderAction:(UISlider *)sender {
    
    self.musicManager.currentTime = sender.value;
    [self.progressTimer fire];
}

#pragma mark - Primary Method
//播放音乐
- (void)primaryMusicPlay {
    MKMusciModel *model = self.musicList[self.musicIndex];
    NSURL *url = [[NSBundle mainBundle] URLForResource:model.mp3 withExtension:nil];
    [self.musicManager playMusic:url];
    //刷新UI
    [self primaryUpdateMusicInfo:model];
    //加载对应的歌曲
    NSURL *lyricsUrl = [[NSBundle mainBundle] URLForResource:model.lrc withExtension:nil];
    self.lyricsList = [self.lyricsTool lyricsWithLRUrl:lyricsUrl];
    self.title = model.name;
    //开始定时器
    [self.progressTimer fire];
    [self lockScreenAction];
    
}

- (void)primaryUpdateMusicInfo:(MKMusciModel *)model {
    //歌手
    self.singerLbl.text = model.singer;
    //歌名
    self.songNameLbl.text = model.name;
    //歌手图片
    self.singerInfosImageView.image = [UIImage imageNamed:model.image];
    //歌词信息
    self.infoLbl.text = model.album;
    //背景图片
    self.bgImageView.image = [UIImage imageNamed:model.image];
    //时间
    self.leftTimeLbl.text = @"00:00";
    self.rightTimeLbl.text = [self.musicTool formatterTimeWithTimeInterval:self.musicManager.duration] ;
    //重置进度条
    self.progressSlider.value = 0.0;
    //更新进度条的最大值
    self.progressSlider.maximumValue = self.musicManager.duration;
}

- (void)progressTimerAction {
    
    self.leftTimeLbl.text = [self.musicTool formatterTimeWithTimeInterval:self.musicManager.currentTime];
    self.progressSlider.value = self.musicManager.currentTime;
    //旋转
    CGFloat angle = 3 / 180.0 * M_PI;
    self.singerInfosImageView.transform = CGAffineTransformRotate(self.singerInfosImageView.transform, angle);
   //更新歌词
    [self primaryUpdateLyrics];
}

- (void)primaryUpdateLyrics {
    MKLyricsModel *model = self.lyricsList[self.lyricsIndex];
    NSTimeInterval beginTime = model.time;
    MKLyricsModel *nextModel = self.lyricsList[self.lyricsIndex+1];
    NSTimeInterval endTime = nextModel.time;
    if (self.lyricsIndex == self.lyricsList.count-2) {
        endTime = self.musicManager.duration;
    }
    
    NSTimeInterval currentTime = self.musicManager.currentTime;
    if (beginTime>currentTime &&self.lyricsIndex>0) {
        self.lyricsIndex--;
        [self primaryUpdateLyrics];
    }
    if (currentTime>endTime && self.lyricsIndex<self.lyricsList.count-2) {
        self.lyricsIndex++;
        [self primaryUpdateLyrics];
    }
    NSString *content = model.content;
    self.lyricsLbl.text = content;
    self.lyricsLbl.progress = (currentTime - beginTime) / (endTime - beginTime);
    self.lyricsLbl.color = [UIColor colorWithRed:arc4random_uniform(255) / 255.0 green:arc4random_uniform(255) / 255.0 blue:arc4random_uniform(255) / 255.0 alpha:1.0];
}

#pragma mark - 锁屏相关事件
//实现锁屏界面的数据更新
- (void)lockScreenAction {
    MKMusciModel *model = self.musicList[self.musicIndex];
    //通过MediaPlayer框架里面MPNowPlayingInfoCenter来实现锁屏界面的信息
    UIImage *image = [UIImage imageNamed:model.image];
    MKLyricsModel *lyricsModel = self.lyricsList[self.lyricsIndex];
    image = [image imageWithLyrics:lyricsModel.content];
    //MPMediaItemArtwork用在锁屏界面表示图片用
    MPMediaItemArtwork *artwork = [[MPMediaItemArtwork alloc] initWithImage:image];
    MPNowPlayingInfoCenter *infoCenter = [MPNowPlayingInfoCenter defaultCenter];
    infoCenter.nowPlayingInfo = @{
                                  MPMediaItemPropertyTitle:model.album,//专辑名字
                                  MPMediaItemPropertyTitle:model.name,//歌曲名字
                                  MPMediaItemPropertyPlaybackDuration:@(self.musicManager.duration),
                                  MPMediaItemPropertyArtwork:artwork
                                  
                                  };
}

#pragma mark - 来电中断
- (void)interruptionAction:(NSNotification *)notification {
    NSNumber *typeNumber = notification.userInfo[AVAudioSessionInterruptionTypeKey];
    NSUInteger type = [typeNumber unsignedIntValue];
    NSUInteger shouldResume = [notification.userInfo[AVAudioSessionInterruptionOptionKey] unsignedIntValue];
    if (type == AVAudioSessionInterruptionTypeBegan) {
        //来电中断，暂停
        if ([self.musicManager isPlaying]) {
            [self setPlayBtn:self.playBtn];
        }
    }else {
        //来电中断结束，要不要恢复
        if (shouldResume == YES) {
            if ([self.musicManager isPlaying] == NO) {
                [self setPlayBtn:self.playBtn];
            }
        }
        
    }
}

#pragma mark - Getter & Setter
-(NSArray *)musicList {
    if (_musicList == nil) {
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"mlist.plist" withExtension:nil];
        NSArray *array = [NSArray arrayWithContentsOfURL:url];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dict in array) {
            MKMusciModel *model = [MKMusciModel mj_objectWithKeyValues:dict];
            [tempArray addObject:model];
        }
        _musicList = tempArray.copy;
    }
    return _musicList;
    
}

- (NSTimer *)progressTimer {
    if (_progressTimer == nil) {
        _progressTimer = [NSTimer scheduledTimerWithTimeInterval:0.25 target:self selector:@selector(progressTimerAction) userInfo:nil repeats:YES];
    }
    return _progressTimer;
}

@end
